package com.breeze.toolkit.retrofit;

import com.breeze.toolkit.util.ConstantsUtil;
import com.squareup.okhttp.Interceptor;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import java.io.IOException;
import java.util.Map;
import java.util.Set;

/**
 * Created by john on 2016/8/23.
 */
public class OkHttpClientInterceptor implements Interceptor {
	private Map<String, String> mHeaderMap;

	public void setHeaderMap(Map<String, String> map) {
		mHeaderMap = map;
	}

	@Override
	public Response intercept(Chain chain) throws IOException {
		if (chain != null) {
			//需要添加header参数时可以用下面方式添加
			Request request = chain.request();
			if (request != null) {
				Request.Builder builder = request.newBuilder();

				if (mHeaderMap != null && !mHeaderMap.isEmpty()) {
					Set<String> keySet = mHeaderMap.keySet();
					for (String key : keySet) {
						builder.addHeader(key, mHeaderMap.get(key));
					}
					mHeaderMap.clear();
				} else {
					builder.addHeader(ConstantsUtil.CONTENT_TYPE, ConstantsUtil.CONTENT_JSON);
					builder.addHeader(ConstantsUtil.ACCEPT, ConstantsUtil.CONTENT_JSON);
				}

				return chain.proceed(builder.build());
			}
			return chain.proceed(chain.request());
		}
		return null;
	}
}
